package note

import (
	"log/slog"
	"strconv"
	"trader/apps/common/resp"
	"trader/models"

	"github.com/gin-gonic/gin"
	"xorm.io/xorm"
)

func ValidUserTradingAccountMiddleware(engine *xorm.Engine) func(c *gin.Context) {
	slog.Debug("注册中间件：ValidUserTradingAccountMiddleware")
	return func(c *gin.Context) {
		accountId, err := strconv.ParseInt(c.Param("trading_account_id"), 10, 64)
		if err != nil {
			resp.FailParamf(c, "无效参数")
			c.Abort()
			return
		}

		userId := c.GetInt64("userId")
		exist, _ := engine.Where("user_id=? and id=?", userId, accountId).Exist(new(models.TradingAccount))
		if !exist {
			resp.FailPermissionf(c, "无权操作账户")
			c.Abort()
			return
		}

		c.Set("tradingAccountId", accountId)
		c.Next()
	}
}

func ValidStockMiddleware(engine *xorm.Engine) func(c *gin.Context) {
	slog.Debug("注册中间件：ValidStockMiddleware")
	return func(c *gin.Context) {
		accountId := c.GetInt64("tradingAccountId")
		stockId, err := strconv.ParseInt(c.Param("stock_id"), 10, 64)
		if err != nil {
			resp.FailParamf(c, "无效stock参数")
			c.Abort()
			return
		}

		exist, _ := engine.Where("trading_account_id=? and id=?", accountId, stockId).Exist(new(models.Stock))
		if !exist {
			resp.FailParamf(c, "stock 不存在")
			c.Abort()
			return
		}

		c.Set("stockId", stockId)
		c.Next()
	}
}

func ValidPlanMiddleware(engine *xorm.Engine) func(c *gin.Context) {
	slog.Debug("注册中间件：ValidPlanMiddleware")
	return func(c *gin.Context) {
		accountId := c.GetInt64("tradingAccountId")
		stockId := c.GetInt64("stockId")
		planId, err := strconv.ParseInt(c.Param("plan_id"), 10, 64)
		if err != nil {
			resp.FailParamf(c, "无效plan参数")
			c.Abort()
			return
		}

		exist, _ := engine.Where("trading_account_id=? and stock_id=? and id=?", accountId, stockId, planId).Exist(new(models.TransactionPlan))
		if !exist {
			resp.FailParamf(c, "plan 不存在")
			c.Abort()
			return
		}

		c.Set("planId", planId)
		c.Next()
	}
}
